package playerthreads;

import messages.Message;
import torpedoserver.PlayerHandlerThread;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Player2Thread extends Thread{
    private Socket playerSocket;

    public Player2Thread(Socket playerSocket) {
        this.playerSocket = playerSocket;
    }

    @Override
    public void run() {
        Message mes = this.getMessage();
        if(mes.getType().equals("StartBattleMessage")){
            PlayerHandlerThread.player2Ready=true;
            System.out.println("Player1 Ready");
        }
    }

    public Message getMessage() {
        ObjectInputStream ios=null;
        try {
            ios = new ObjectInputStream(this.playerSocket.getInputStream());
        } catch (IOException ex) {
            Logger.getLogger(Player1Thread.class.getName()).log(Level.SEVERE, null, ex);
        }
        Message message=null;
        try {
            message = (Message)ios.readObject();
        } catch (IOException ex) {
            Logger.getLogger(Player1Thread.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Player1Thread.class.getName()).log(Level.SEVERE, null, ex);
        }
        return  message;
    }

    public void SendMess(Message mess) throws IOException{
        OutputStream os = this.playerSocket.getOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(os);
        oos.writeObject(mess);
        oos.flush();
    }
}
